package com.medata.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.medata.dataObject.*;
import com.medata.exeptions.YunExceptions;
import com.medata.service.GlobalsettingService;
import com.medata.service.impl.*;
import com.medata.utils.*;
import com.medata.vo.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author ：zb
 * @date ：Created in 2019/6/12 0012 11:13
 * @description：
 */
@Controller
@Api
@Slf4j
@RequestMapping("/Auditor")
public class AuditorController {
    @Autowired
    private GlobalsettingService globalsettingService;
    @Autowired
    private CategoryServiceImpl categoryService;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private DocobjectServiceImpl docobjectService;
    @Value("${FilePath}")
    private String filePath;
    @Value("${ServerIP}")
    private String ip;
    @Value("${jdbcDriver}")
    private String jdbcDriver;
    @Value("${jdbcUrl}")
    private String jdbcUrl;
    @Value("${jdbcUser}")
    private String jdbcUser;
    @Value("${jdbcPassword}")
    private String jdbcPassword;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TemplatefieldsServiceImpl templatefieldsService;
    @Autowired
    private DefaultValueTableServiceImpl defaultValueTableService;
    @Autowired
    private FjServiceImpl fjService;

    //获取solr全部结果
    @RequestMapping(value = "/solrSearch/{dbid}/{page}")
    @ResponseBody
    public ModelAndView get_solr_all(@PathVariable String dbid, @PathVariable String page) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Category category = categoryService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //是否有获取资料权限
//        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
//        if (hasAuthority == 0) {
//            throw new UnauthorizedException();
//        }
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), null, null, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;
        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < 5; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                value.add(field.getFieldvalue());
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 2).getFieldvalue());
            String sql = "select ischeck from " + category.getDba() + " where docid = " + value.get(0);
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    String ischeck = rs.getString(1);
                    value.add(ischeck);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new YunExceptions(0, "solr获取分页数据的时候,查询数据库出错");
            }
            //20190621修改获取ischeck数据
//            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);
        }
        colums.add("更新时间");
//        colums.add("已上传文件");
        colums.add("是否已通过审核");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("searchList", searchFields);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc", category.getDc());
        mv.addObject("dba", category.getDba());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.setViewName("solrTable2");
        mv.addObject("auditor", 1);
        return mv;
    }

    //查看详细内容
    @RequestMapping(value = "/zlupdate/{dbid}/{docid}/{str}", method = RequestMethod.GET)
    public ModelAndView test(@PathVariable Integer dbid, @PathVariable String docid, @PathVariable String str) {
        ModelAndView mv=new ModelAndView();
        String title=null;
        //增加资料信息
        Category category = categoryService.findByDbid(Integer.valueOf(dbid));
        String sql = "SELECT * from " + category.getDba() + " where docid=" + docid;
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        String xml = null;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                title=rs.getString(2);
                xml = rs.getString(3);
            }
        } catch (Exception e) {
            throw new YunExceptions(0, "修改客户资料时,数据库获取信息异常");
        }
        Map<String,String> valueMap = XmlUtil.getValues(xml, Integer.valueOf(dbid), 100);

        //是否已经录入供应商名单
        if (dbid==16){
            DefaultValueTable vTable = defaultValueTableService.findByDefValuesAndRefId(title, 102);
            if (vTable==null){
                mv.addObject("hasInput","0");
            }else {
                mv.addObject("hasInput","1");
            }
        }else{
            mv.addObject("hasInput","0");
        }
        List<Templatefields> templatefields = templatefieldsService.getByDbidOrderBySequence(dbid);
        List<FieldsVO> fieldsVOS=new ArrayList<>();
        for (Templatefields templatefield:templatefields){
            if (templatefield.getInputType()==0){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("0");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                value=XmlUtil.getUnreplace(value);
                fieldsVO.setValue(value);
                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==2){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("2");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                List<String> values=new ArrayList<>();
                List<DefaultValueTable> tables = defaultValueTableService.findByRefId(templatefield.getRefId());
                for (DefaultValueTable table:tables){
                    values.add(table.getDefValues());
                }
                fieldsVO.setValuelist(values);
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                fieldsVO.setValue(value);

                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==4|templatefield.getInputType()==7){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType(String.valueOf(templatefield.getInputType()));
                fieldsVO.setKey(templatefield.getTpFieldName());
                fieldsVO.setIsneed(templatefield.getIsNeed());
                //添加数据信息
                if (templatefield.getInputType()==4){
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    fieldsVO.setValue(value);
                }else{
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    String[] values = value.split(",");
                    List<String> list = Arrays.asList(values);
                    fieldsVO.setValues(list);
                }
                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==6){
                if (templatefield.getRankREFID()==null){
                    FieldsVO fieldsVO=new FieldsVO();
                    fieldsVO.setDesc(templatefield.getTpFieldDesc());
                    fieldsVO.setInputType("6");
                    fieldsVO.setKey(templatefield.getTpFieldName());
                    List<String> values=new ArrayList<>();
                    List<DefaultValueTable> tables = defaultValueTableService.findByRefId(templatefield.getRefId());
                    for (DefaultValueTable table:tables){
                        values.add(table.getDefValues());
                    }
                    fieldsVO.setValuelist(values);

                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    fieldsVO.setValue(value);

                    List<SonFieldsVO> sons=new ArrayList<>();
                    List<Templatefields> templatefieldsList = templatefieldsService.getByRankREFID(String.valueOf(templatefield.getRefId()));
                    for (Templatefields tp:templatefieldsList){
                        SonFieldsVO sonFieldsVO=new SonFieldsVO();
                        sonFieldsVO.setDesc(tp.getTpFieldDesc());
                        sonFieldsVO.setKey(tp.getTpFieldName());
                        sonFieldsVO.setInputType(String.valueOf(tp.getInputType()));
                        List<String> values1=new ArrayList<>();
                        List<DefaultValueTable> tables1 = defaultValueTableService.findByRefId(tp.getRefId());
                        for (DefaultValueTable table:tables1){
                            values1.add(table.getDefValues());
                        }
                        sonFieldsVO.setValuelist(values1);

                        String sonfieldDesc = tp.getTpFieldDesc();
                        String sonvalue = DataUtil.getValue(sonfieldDesc, valueMap);
                        sonFieldsVO.setValue(sonvalue);

                        List<GsonFieldsVO> gsons=new ArrayList<>();
                        List<Templatefields> tpList = templatefieldsService.getByRankREFID(String.valueOf(tp.getRefId()));
                        for (Templatefields tp1:tpList){
                            GsonFieldsVO gsonFieldsVO=new GsonFieldsVO();
                            gsonFieldsVO.setDesc(tp1.getTpFieldDesc());
                            gsonFieldsVO.setKey(tp1.getTpFieldName());
                            List<String> values2=new ArrayList<>();
                            List<DefaultValueTable> tables2 = defaultValueTableService.findByRefId(tp1.getRefId());
                            for (DefaultValueTable table:tables2){
                                values2.add(table.getDefValues());
                            }
                            gsonFieldsVO.setValuelist(values2);
                            String gsonfieldDesc = tp1.getTpFieldDesc();
                            String gsonvalue = DataUtil.getValue(gsonfieldDesc, valueMap);
                            String[] gsonvalues = gsonvalue.split(",");
                            List<String> gsonlist = Arrays.asList(gsonvalues);
                            gsonFieldsVO.setValues(gsonlist);
                            gsons.add(gsonFieldsVO);
                        }
                        sonFieldsVO.setGsons(gsons);
                        sons.add(sonFieldsVO);
                    }
                    fieldsVO.setSons(sons);
                    fieldsVOS.add(fieldsVO);
                }
            }
        }
        String[] split = str.split("@");
        if (split.length == 2) {
            mv.addObject("ss", split[0]);
            mv.addObject("page", split[1]);
        } else {
            mv.addObject("page", split[0]);
        }
        if (dbid==12){
            Fj fjxx = fjService.getByDocid(Integer.valueOf(docid));
            mv.addObject("fjxx",fjxx);
        }


        mv.addObject("fieldsVOS",fieldsVOS);
        mv.setViewName("zlUpdateForm");
        mv.addObject("dc", category.getDc());
        mv.addObject("dbid", dbid);
        //添加文件信息
        List<Docobject> docLists = docobjectService.findByDocidAndDbid(docid, String.valueOf(dbid));
        mv.addObject("docLists", docLists);
        mv.addObject("auditor",1);
        return mv;
    }

    //单文件下载
    @RequestMapping(value = "fileDown/{objId}")
    public void fileDwon(HttpServletResponse response, @PathVariable String objId) {
        try {
            Docobject objectid = docobjectService.findAllByObjectid(objId);
            String path = objectid.getServerfullpath();
            String dbaname = categoryService.findByDbid(Integer.valueOf(objectid.getDbid())).getDba();
            File file = new File(filePath + "/" + dbaname + "/" + path);
            String tempPath = filePath + "/tempFiles/" + dbaname + "/" + UidUtil.getUid() + "/" + objectid.getObjectfilename();
            File tempfile = new File(tempPath);
            FileUtils.copyFile(file, tempfile);
            String filename = objectid.getObjectfilename();
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            FileCopyUtils.copy(new FileInputStream(tempfile), response.getOutputStream());
        } catch (Exception e) {
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('文件资源异常,请联系管理员');history.go(-1)</script>");
                writer.flush();
                writer.close();
            } catch (Exception e1) {
                throw new YunExceptions(0, "下载单个文件的时候,资源异常");
            }
        }
        return;
    }

    //文件在线预览
    @RequestMapping(value = "fileOpen/{objid}", method = RequestMethod.GET)
    public ModelAndView fileOpen(@PathVariable String objid, HttpServletResponse response) {
        ModelAndView mv=new ModelAndView();
        Docobject docobject = docobjectService.findAllByObjectid(objid);
        String filename=docobject.getObjectfilename();
        String uid = UidUtil.getUid();
        String dbaname=categoryService.findByDbid(Integer.valueOf(docobject.getDbid())).getDba();
        String tempPath = filePath + "/tempFiles/"+dbaname+"/"+uid;
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        File file1 = new File(filePath+"/"+dbaname+"/"+docobject.getServerfullpath());
        filename=filename.replaceAll("%","");
        String newName = tempPath + "/" + filename;
        File file2 = new File(newName);
        if (filename.endsWith(".pdf")){
            try {
                FileUtils.copyFile(file1, file2);
                String url=ip + "/directionary/pdfjs/web/viewer.html?file="+ip+"tempFiles/"+dbaname+"/"+uid+"/"+filename;
                mv.addObject("pdfname",docobject.getObjectfilename());
                mv.addObject("pdfurl",url);
                long length = file2.length();
                long c=10485760;
                long time = length / c;
                time=time*1000+1000;
                mv.addObject("waitTime",time);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mv.setViewName("pdfview");
            return mv;
        }else {
            InputStream is=null;
            OutputStream os=null;
            try {
                response.setContentType("image/jpeg");
                FileUtils.copyFile(file1, file2);
                response.addHeader("Content-Length", "" + file2.length());
                is=new FileInputStream(file2);
                os=response.getOutputStream();
                IOUtils.copy(is,os);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (os!=null){
                        os.flush();
                        os.close();
                    }
                    if (is!=null){
                        is.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new YunExceptions(0,"浏览图偏,关闭流bug");
                }
            }
            return null;
        }
    }

    //获取solr搜索结果
    @RequestMapping(value = "solrSearch/{dbid}/{word}/{str}/{page}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getObjects(@PathVariable String dbid, @PathVariable String word, @PathVariable String str, @PathVariable String page) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Category category = categoryService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //是否有获取资料权限
//        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
//        if (hasAuthority == 0) {
//            throw new UnauthorizedException();
//        }
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), word, str, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;
        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < 5; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                value.add(field.getFieldvalue());
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 2).getFieldvalue());
            String sql = "select ischeck from " + category.getDba() + " where docid = " + value.get(0);
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    String ischeck = rs.getString(1);
                    value.add(ischeck);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new YunExceptions(0, "solr获取分页数据的时候,查询数据库出错");
            }
            //20190621更改审核信息
//            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);
        }
        colums.add("更新时间");
//        colums.add("已上传文件");
        colums.add("是否已通过审核");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("searchList", searchFields);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("str", str);
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc", category.getDc());
        mv.addObject("dba", category.getDba());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.setViewName("solrTable2");
        mv.addObject("word", word);
        mv.addObject("auditor", 1);
        return mv;
    }

    //提交审核信息
    @RequestMapping(value = "/zlPass", method = RequestMethod.POST)
    @ResponseBody
    public void zlpost(HttpServletResponse response, String docid,Integer dbid) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Category category = categoryService.findByDbid(dbid);
        String sql="update "+category.getDba()+" set isCheck = 1 where docid = "+docid;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.execute();
            SolrUtils.updateIndex(globalsettingService,dbid,category.getDba(),0,docid);
        }catch (Exception e){
            e.printStackTrace();
            throw new YunExceptions(0,"通过审核出现bug");
        }
        //修改excel文件
        String excelPath=filePath+category.getDc()+".xlsx";
        File excelF=new File(excelPath);
        try {
            XSSFWorkbook xssfSheets=new XSSFWorkbook(new FileInputStream(excelF));

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //拒绝审核
    @RequestMapping(value = "/zlrefuse", method = RequestMethod.POST)
    @ResponseBody
    public void zlrefuse(HttpServletResponse response, String docid,Integer dbid) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Category category = categoryService.findByDbid(dbid);
        String sql="update "+category.getDba()+" set isCheck = 0 where docid = "+docid;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.execute();
            SolrUtils.updateIndex(globalsettingService,dbid,category.getDba(),0,docid);
        }catch (Exception e){
            e.printStackTrace();
            throw new YunExceptions(0,"通过审核出现bug");
        }
    }

    //导出Excel信息
    @RequestMapping(value = "ExcelGet/{dbid}", method = RequestMethod.GET)
    public void getExcel(HttpServletResponse response, @PathVariable Integer dbid) {
        Category category = categoryService.findByDbid(dbid);
        String fPath=filePath+"/tempFiles/"+UidUtil.getUid()+"/";
        File f=new File(fPath);
        if (!f.exists()){
            f.mkdirs();
        }
        File file=new File(fPath+category.getDba()+".zip");
        File intFile=new File(filePath+"/excels/"+category.getDba());
        try {
            ZipOutputStream out=new ZipOutputStream(new FileOutputStream(file));
            BufferedOutputStream bos=new BufferedOutputStream(out);
            File[] files=intFile.listFiles();
            if (files.length>0){
                for (int i=0;i<files.length;i++){
                    out.putNextEntry(new ZipEntry(files[i].getName()));
                    FileInputStream fos=new FileInputStream(files[i]);
                    BufferedInputStream bis=new BufferedInputStream(fos);
                    int tag;
                    while ((tag=bis.read())!=-1){
                        out.write(tag);
                    }
                    bis.close();
                    fos.close();
                }
            }
            bos.close();
            out.close();
            response.addHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes()));
            response.setContentType("application/octet-stream");
            IOUtils.copy(new FileInputStream(file),response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //删除原始索引数据
    @RequestMapping(value = "/solrDelete/{dbid}", method = RequestMethod.GET)
    public void solrDelete(@PathVariable Integer dbid) {
        Integer nums=160;
        Category category = categoryService.findByDbid(dbid);
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        while (nums>0){
            String sql="select top 1000 DocID from "+category.getDba()+" where IndexFlag =1 and docid not in ( select top "+nums*1000+" DocID from "+category.getDba()+" where IndexFlag =1 )";
            Connection connection = session.connection();
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                String dcid=null;
                while (rs.next()){
                    dcid = rs.getString(1);
                    if (dcid!=null){
                        SolrUtils.deleteIndex(globalsettingService,category.getDba(),dcid);
                        String sql2="update "+category.getDba()+" set IndexFlag = 0 where docid = " + dcid;
                        PreparedStatement ps2 = connection.prepareStatement(sql2);
                        ps2.execute();
                    }
                }
                nums--;
            }catch (Exception e){
                e.printStackTrace();
                throw new YunExceptions(0,"更新索引的时候出现bug");
            }
        }
    }

    //更新检索数据2
    @RequestMapping(value = "/solrUpdate/{dbid}", method = RequestMethod.GET)
    public void solrUpdate2(@PathVariable Integer dbid, HttpServletResponse response) {
        Category category = categoryService.findByDbid(dbid);
        SolrUtils.insertAllIndexs(globalsettingService,category.getDba(),dbid);
        String sql="update "+category.getDba()+" set indexFlag= '1' where indexFlag= '0'";
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        try {
            Statement statement = connection.createStatement();
            statement.execute(sql);
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //xml在线预览
    @RequestMapping(value = "fileOpen/{objid}/xml", method = RequestMethod.GET)
    @ResponseBody
    public List<String> fileOpen2(@PathVariable String objid) {
        Docobject docobject = docobjectService.findAllByObjectid(objid);
        String dbaname = categoryService.findByDbid(Integer.valueOf(docobject.getDbid())).getDba();
        File file = new File(filePath + "/" + dbaname + "/" + docobject.getServerfullpath());
        try {
            List<String> list = FileUtils.readLines(file, "utf-8");
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
